package com.zhuang.springbootredis.lock;

import redis.clients.jedis.Jedis;

import java.util.Arrays;
import java.util.List;

public class RedisLockExample {
    public static void main(String[] args) {

        // 基础锁使用示例
        Jedis jedis = new Jedis("localhost", 6379);
        try (RedisDistributedLock lock = new RedisDistributedLock(jedis, "order_lock", 30)) {
            if (lock.acquire(5000)) {
                System.out.println("获取基础锁成功");
                // 执行业务逻辑
                Thread.sleep(2000);
            } else {
                System.out.println("获取基础锁失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }

        // RedLock使用示例
        List<Jedis> jedisClients = Arrays.asList(
                new Jedis("localhost", 6379),
                new Jedis("localhost", 6380),
                new Jedis("localhost", 6381)
        );

        try (RedLock redLock = new RedLock(jedisClients, "global_lock", 30)) {
            if (redLock.acquire(5000)) {
                System.out.println("获取RedLock成功");
                // 执行业务逻辑
                Thread.sleep(2000);
            } else {
                System.out.println("获取RedLock失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedisClients.forEach(Jedis::close);
        }
    }
}